package com.hgkj.cloud.customer.file;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import com.hgkj.cloud.customer.common.FileSaver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class FileSourceGenerator {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    //本地目录
    @Value("${fileSourceGenerator.clientDir}")
    private String clientDir;
    //图片服务器的访问目录 如果"/"开头表示在同一台服务器上,如果以http开头表示在不同的机器
    @Value("${fileSourceGenerator.serverPath}")
    private String serverPath;

    public String getClientDir() {
        return clientDir;
    }

    public void setClientDir(String clientDir) {
        this.clientDir = clientDir;
    }

    public String getServerPath() {
        return serverPath;
    }

    public void setServerPath(String serverPath) {
        this.serverPath = serverPath;
    }

    public String generator(FileSaver fs) throws IOException {
        String fileExt = fs.getExtension();
        if (!fileExt.startsWith(".")) fileExt = "." + fileExt;
        logger.info("++开始====新建临时文件");
        File tmpFile = new File(clientDir, UUID.randomUUID().toString() + fileExt);
        // File tmpFile = File.createTempFile("cloud", fileExt, file);
        logger.info("++开始====" + tmpFile + "设置虚拟机关闭时删除临时文件");
        // tmpFile.deleteOnExit();
        logger.info("++开始====" + tmpFile + "保存文件");
        fs.saveFile(tmpFile);
        logger.info("++开始====" + tmpFile + "设置文件");
        fs.setLocalFile(tmpFile);
        return serverPath + tmpFile.getName();
    }

    public String generatorOpen(FileSaver fs) throws IOException {
        String fileExt = fs.getExtensionOpen();
        if (!fileExt.startsWith(".")) fileExt = "." + fileExt;

        File tmpFile = File.createTempFile("cloud", fileExt, new File(clientDir));
        tmpFile.deleteOnExit();
        fs.saveFileOpen(tmpFile);

        return serverPath + tmpFile.getName();

    }

}
